package respository

import (
	"awesomeProject/goprpoject/test11/common"
	"awesomeProject/goprpoject/test11/model"

	"github.com/jinzhu/gorm"
)

type CategoryRepository struct {
	DB *gorm.DB // 链接器
}

// 创建CategoryRepository
func NewCategoryRepository() CategoryRepository {
	return CategoryRepository{DB: common.GetBD()} // 返回DB
}

// 新增
func (c CategoryRepository) Create(name string) (*model.Category, error) {
	category := model.Category{
		Name: name,
	}
	if err := c.DB.Create(&category).Error; err != nil {
		return nil, err
	}
	return &category, nil
}

// 修改

func (c CategoryRepository) Upate(category model.Category, name string) (*model.Category, error) {
	if err := c.DB.Model(&category).Update("name", name).Error; err != nil {
		return nil, err
	}
	return &category, nil
}

// 查
func (c CategoryRepository) SelecBytId(id int) (*model.Category, error) {
	var category model.Category
	if err := c.DB.First(&category, id).Error; err != nil {
		return nil, err
	}
	return &category, nil
}

// 删除
func (c CategoryRepository) DeleteByID(id int) error {

	if err := c.DB.Delete(model.Category{}, id).Error; err != nil {
		return err
	}
	return nil
}
